/*************************
* STICK OBJECT
*************************/
function Stick(config) {
	
	var quicktigame2d = require('com.googlecode.quicktigame2d');
	
	var conf = {
		angle: 5,
		speed: 5
	};
	
	//copying configuration
	for(var opt in config){
		conf[opt]= config[opt];
	}
	
	var moving = false;
	
	var self = quicktigame2d.createSprite({
  		image: 'images/gorodki.png'
	});
	
	this.size = Math.max(self.width, self.height);
	
	//position sprite at the bottom of screen on y axis
	var startPosition = Titanium.Platform.displayCaps.platformHeight - this.size;
	self.y = startPosition;
	//position sprite in the center of screen on x axis
	self.x = (Titanium.Platform.displayCaps.platformWidth - this.size)/2;
	
	
	this.getSprite = function(){
		return self;
	};
	
	this.getAngle = function(){
		return self.angle;
	};
	
	this.move = function(){
		moving = true;
	};
	
	this.isMoving = function(){
		return moving;
	};
	
	this.step = function(){
		//rotate stick
		self.rotate(self.angle + conf.angle);
		
		//move stick
		if(moving){
			if(self.y > -this.size)
			{
				self.y -= conf.speed;
			}
			else
			{
				moving = false;
				self.y = startPosition;
			}
		}
	};
	
	//get last measure time
	var lastTime = new Date().getTime();
 
	//get time offset
	var offset = 100;
 
	//create filter (value between 0.5 and 1, where 1 is no filtering)
	var filter = 1.0;
 
	//last values
	var last_x = 0;
 
	//get accelerometer data
	Titanium.Accelerometer.addEventListener('update',function(e)
	{
	    //get current time
	    var now = new Date().getTime();
     
	    //check if time offset is passed
	    if(lastTime + offset < now)
	    {
	        //use last value, apply filter and store new value
	        last_x = e.x * filter + last_x * (1 - filter);
 
	        //move stick accordingly (5 times to emphasize small movement)
	        var move = last_x*5;
	        //check if stick won't move outside the screen
	        if(self.x - move >= 0 && self.x - move <= Titanium.Platform.displayCaps.platformWidth - self.width)
	        {
	        	//apply movement
	        	self.x -= move;
	        }
         
    	    //store last update time
    	    lastTime = now;
   	 	}
	});
};

module.exports = Stick;
